﻿## =====================================================================
## Title       : spAdm-Kerberos
## Description : Check Kerberos config for SharePoint 
## Author      : Neil Spencer, Simon Kemp 
## Date        : 06 - October 2013
## Usage       : Build required SPNs for SharePoint 
##             : Check Kerberos on Server
## Notes       :  
## Change log  : 
## =====================================================================

# Set up script parameters and default values
param ([switch] $debug = $False,
       [switch] $checkServer,
       [switch] $help);


# Change working directory
CD ([System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition))


# Set global parameters for the script
function SetGlobalParameters() {
    # Logging level
    if ($debug) {

        $script:DebugPreference = "Continue";

    }

    $Script:SetspAdmKerberos = ((Get-Location).Path + "\set-spnAdm-Kerberos.ps1")
    $Script:logfile = (Get-Location).Path + "\log\" + ("spAdm" + (gc env:computername) + (get-date -Format s) + ".log").Replace(":","")

    # Used as part if SPN unique check
    $Domain = ($([System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()).name).Split(".")
    foreach ($node in $Domain) {$DomainDN = $DomainDN + "DC=" + $node + ","}
    $DomainDN = $DomainDN.trim(",")
            
}
     
     
# Display the help message
function DisplayUsage()
{
    $HelpText = @"

    DESCRIPTION:
    NAME: spAdm-Kerberos
    
    The C2WTS will be set to constrained delegation, delgating to itself.
    
    All Service Applications apart from the BSCS will be set to constrained delegation. 
    Delegating to itself, you will need to add additional SPN's for cubes etc.

    As the above SPNs are fake (dummy), if any SPN \ Delagation is in place
    at the required level no additioanl SPNs or deleagations will be created.
    
    All Web applications will be set as basic delegation, This may not suit
    your environment..


"@

    $HelpText;
}  

# Main entry point
function Main() {

    Cls;
    
    # Load SharePoint Command lets 
    Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
    
    #Set Global Parameters
    SetGlobalParameters
                
    # As Scipt has only been tested against 2013, lets check version
    if (((Get-SPFarm).buildversion.major -ne "15") ) {Write-Host " - The script has not been validated against this version of SharePoint ... " -ForegroundColor DarkRed; sleep 3; }

    # Load helpers 
    $Helpers = @(Get-ChildItem (Get-Location).Path) | Where-Object {$_.name -like "*Helpers*"}
       
    # Load Helpers 
    if (([string]::IsNullOrEmpty($Helpers))) { # Helpers should be in the same folder ...
    
        Write-Host " - Helper file(s) not found in current directory  - aborting" -ForegroundColor Red; break 

    } else {  # load helper files 
           

        foreach ($Helper in $Helpers) {$ImportHelper = Resolve-Path ((Get-Location).Path + "\$Helper"); ."$ImportHelper"}

    }

    
    if($Help) {DisplayUsage; break}

    # Create log foler if required 
    New-spAdm-folder -path ((Get-Location).Path + "\log\")
    
    # Stop any Current Transcribing
    if ($psISE -eq $false) {
    try{Stop-Transcript|out-null} catch [System.InvalidOperationException]{}
    }

    spAdm-Start-Transcript $logfile 
    
    Write-Warning "Where the local system account is used in place of domain accounts (C2WTS etc...) a SPN request will not be generated"
    Write-Host ""
    
    Write-Host -ForegroundColor Cyan "*** Start of script ***"
    
    Write-Host "  - Flushing Dns" -NoNewline
    ipconfig /flushdns | Out-Null; write-spAdm -Result $? -ErrorMessage "Failed to flush dns on local machine"

        
    If ($checkServer)  {

    # Check server functionality planned in future release

    } else {
    
        Write-Host "  - Building script to create SPN's" -NoNewline; sleep 3; Write-Host " - Creating base $SetspAdmKerberos"
        build-spAdm-Spn-Base

        Write-Host ""
        Write-Host "- Building Spn's for Claims to Windows Token Service"  -ForeGroundColor Cyan
        Write-Host "  Arbitrary SPN will be added if deemed necessary" -ForegroundColor Yellow
        build-spAdm-Spn-C2Wts
        
        Write-Host ""
        Write-Host "- Building required Spn's for SharePoint Service Applications"  -ForeGroundColor Cyan
        Write-Host "  If constrained delegation is the target state and no SPN is available, an arbitrary SPN will be created" -ForegroundColor Yellow
        build-spAdm-Spn-ServiceApplications
        
        Write-Host ""
        Write-Host "- Building required Spn's for SharePoint Web Applications"  -ForeGroundColor Cyan
        build-spAdm-Spn-WebApplications
        
        Write-Host ""
        Write-Host "- Getting all database Servers that may require a SPN"  -ForeGroundColor Cyan
        build-spAdm-Spn-sql

        Write-Host ""
        spAdm-Stop-Transcript $logfile | Out-Null
        Write-Host ""
        Write-Host "*** End of script ***" -ForeGroundColor Cyan
        
        Write-Host "`r`n`r`n"
        Write-Host " - Next Steps" -ForegroundColor Green -BackgroundColor DarkBlue; sleep 3
        Write-Host "   - 1. Review  $SetspAdmKerberos"
        Write-Host "   - 2. Add service accounts for SQL as required"
        Write-Host "   - 3. Add any additional datasources"
        Write-Host "   - 4. Run Set-spAdm-Kerberos.ps1 to create SPN's"
        Write-Host "   - 5. Rerun this script to validate SPN's"
        Write-Host "   - 6. Run this script with -CheckServer switch to validate server ... <available in future script release>"
        Write-Host "   - 7. Be Happy "
        Write-Host "`r`n"
        Write-Warning "This script will only configure basic Kerberos delegation on web applications"; sleep 3
        Write-Host "`r`n"
            
    }

    
}

Main